using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;

public class DeployerConfigFactory : MonoBehaviour
{
    // 一个字典用以缓存类型
    private static Dictionary<string, Type> typeCache = new Dictionary<string, Type>();

    /// <summary>
    /// 创建技能部署器
    /// </summary>
    /// <param name="skillData"></param>
    /// <returns></returns>
    public static MonoBehaviour AddSkillDeployer(SkillData skillData, GameObject prefab)
    {
        string className = string.Format("{0}SkillDeployer", skillData.deployerType.ToString());
        Type type = CheckForTypeCache(className);
        return prefab.AddComponent(type) as MonoBehaviour;
    }

    /// <summary>
    /// 创建范围选择算法
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public static ISkillSelector CreateSkillSelector(SkillData data) 
    {
        //if (data.selectType == SelectType) return null;
        string className = string.Format("{0}SkillSelector", data.selectType.ToString());
        return CreateObject<ISkillSelector>(className);
    }

    /// <summary>
    /// 创建效果算法
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public static BaseImpactEffect[] CreateImpactEffects(SkillData data)
    {
        BaseImpactEffect[] impacts = new BaseImpactEffect[data.impactType.Count];
        for (int i = 0; i < data.impactType.Count; i++)
        {
            string className = string.Format("{0}Impact", data.impactType[i].ToString());
            impacts[i] = CreateObject<BaseImpactEffect>(className);
            impacts[i].skillData = data;
        }
        return impacts;
    }

    /// <summary>
    /// 创建对应算法
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="className"></param>
    /// <returns></returns>
    private static T CreateObject<T>(string className) where T : class 
    {
        Type type = CheckForTypeCache(className);

        return Activator.CreateInstance(type) as T;
    }

    /// <summary>
    /// 在类型缓存中检查是否存在匹配的类型
    /// </summary>
    /// <param name="className"></param>
    /// <returns></returns>
    private static Type CheckForTypeCache(string className)
    {
        if (!typeCache.TryGetValue(className, out Type type))
        {
            // 如果缓存中没有该类型，反射获取并缓存
            type = Type.GetType(className);
            if (type != null)
            {
                typeCache[className] = type;
            }
            else
            {
                Debug.LogError($"Type {className} not found.");
                return null;
            }
        }

        return type;
    }
}